package asia.doing.service.manage;


import asia.doing.common.enums.ResultCodeEnum;
import asia.doing.common.enums.RoleEnum;
import asia.doing.common.exception.CustomException;
import asia.doing.common.utils.TokenUtils;
import asia.doing.entity.Account;
import asia.doing.entity.Article;
import asia.doing.entity.User;
import asia.doing.mapper.ArticleMapper;
import asia.doing.mapper.UserMapper;
import cn.hutool.core.util.ObjectUtil;
import com.auth0.jwt.JWT;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service(value = "manageUserService")
public class UserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private ArticleMapper articleMapper;

    public List<User> selectUser(User user) {
        Article article = new Article();
        article.setUserId(user.getId());
        List<Article> articles = articleMapper.selectAll(article);
        List<Integer> articlesIds = new ArrayList<>();
        articles.forEach(article1 -> {
            articlesIds.add(article1.getId());
        });
        List<User> users = userMapper.selectAll(user);
        Integer[] articleIdsArray = articlesIds.toArray(new Integer[articlesIds.size()]);
        users.get(0).setArticles(articleIdsArray);
        return users;
    }

    public void addUser(User user) {
        userMapper.insert(user);
    }

    public void updateUser(User user) {
        userMapper.updateById(user);
    }

    public void deleteUser(Integer id) {
        userMapper.deleteById(id);
        //将用户下的所有文章设置为空
        articleMapper.updateUserIdToZeroByUserId(id);
    }

    public PageInfo<User> selectPage(User user, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        //注意:这里获取到的信息是重复的
        List<User> list = userMapper.selectAll(user);
        System.out.println(list.size());
        PageInfo<User> pageInfo = PageInfo.of(list);
//      List<Activity> activityList = pageInfo.getList(); 可以获取所有列表循环做其他事情
        return pageInfo;
    }


    /**
     * 登录
     * @param account
     * @return
     */
    public Account login(Account account) {
        User user = new User();
        BeanUtils.copyProperties(account, user);
        //登录操作
        List<User> users = userMapper.selectAll(user);
        System.out.println("获取到的长度为" + users.size());

        if (users.isEmpty()) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        } else {
            User firstUser = users.get(0);
            if (!account.getPassword().equals(firstUser.getPassword())) {
                throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
            }
        }

        // 生成token
        String tokenData = users.get(0).getId() + "-" + RoleEnum.ADMIN.name();
        String token = TokenUtils.createToken(tokenData, users.get(0).getPassword());

        Account account1 = new Account();
        account1.setUsername(users.get(0).getUsername());
        account1.setIntroduce(users.get(0).getIntroduce());
        account1.setAvatar(users.get(0).getAvatar());
        account1.setId(users.get(0).getId());
        account1.setToken(token);

        return account1;
    }

    public void register(Account account) {
        User user = new User();
        BeanUtils.copyProperties(account, user);
        this.addUser(user);
    }



    /**
     * 修改密码
     */
    public void updatePassword(Account account) {
        User user = new User();
        BeanUtils.copyProperties(account, user);
        List<User> users = userMapper.selectAll(user);
        if (ObjectUtil.isNull(users.get(0))) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!account.getPassword().equals(users.get(0).getPassword())) {
            throw new CustomException(ResultCodeEnum.PARAM_PASSWORD_ERROR);
        }
        users.get(0).setPassword(account.getNewPassword());
        userMapper.updateById(users.get(0));
    }


    /**
     * 验证
     */
    public User verify(String token) {
        String userRole = JWT.decode(token).getAudience().get(0);
        String userId = userRole.split("-")[0];
        String role = userRole.split("-")[1];
        User user = new User();
        user.setId(Integer.valueOf(userId));
        List<User> users = this.selectUser(user);
        if (ObjectUtil.isNull(users.get(0))) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        return users.get(0);
    }
}
